﻿using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Xml;
using Devv.Core.Erroo;

namespace Devv.Threeter
{
	class ShortUrlManager
	{
		#region Constants

		internal const String BITLY_USER = "devv";
		internal const String BITLY_KEY = "R_c8ffabe12c94240de391c8f4880e3f2a";

		#endregion

		#region Bit.ly API

		private static String GetFromBitLy(String url)
		{
			try
			{
				using (WebClient web = new WebClient())
				{
					return ParseBitLy(web.DownloadString("http://api.bit.ly/shorten?version=2.0.1&format=xml&login=" + Properties.Settings.Default.BitLyUser + "&apiKey=" + Properties.Settings.Default.BitLyPassword + "&longUrl=" + url));
				}
			}
			catch
			{
				return url;
			}
		}

		private static String ParseBitLy(String response)
		{
			XmlDocument xml = new XmlDocument();

			try
			{
				xml.LoadXml(response);

				XmlNode node = xml.DocumentElement.SelectSingleNode("//shortUrl");

				if (node != null)
				{
					return node.InnerText;
				}
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Could not make URL sorter using Bit.ly.");
			}

			return String.Empty;
		}

		#endregion

		#region Parsing text

		public static String Parse(String text)
		{
			Regex r = new Regex(@"((www\.|(http|https|ftp|news|file)+\:\/\/)[&#95;.a-z0-9-]+\.[a-z0-9\/&#95;:@=.+?,##%&_~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])", RegexOptions.IgnoreCase);
			MatchCollection matches = r.Matches(text);

			for (Int32 i = 0; i < matches.Count; i++)
			{
				String value = matches[i].Value;
				Boolean hasSubdir = value.Replace("http://", String.Empty).Contains("/");

				if (hasSubdir && value.Length > 25 && !value.Contains("http://bit.ly"))
				{
					text = text.Replace(value, GetFromBitLy(value));
				}
			}

			return text;
		}

		#endregion
	}
}